import { articleApi } from '@/entities/article';
import { authReducer } from '@/entities/auth';
import { companyApi } from '@/entities/company';
import { productApi } from '@/entities/course';
import { profileReducer } from '@/entities/profile';
import { ratingApi } from '@/entities/rating';
import { configureStore } from '@reduxjs/toolkit';
import { setupListeners } from '@reduxjs/toolkit/query';
import { createWrapper } from 'next-redux-wrapper';
import { combineReducers } from 'redux';

import { routerReducer } from './router.slice';

const rootReducer = combineReducers({
  auth: authReducer,
  profile: profileReducer,
  router: routerReducer,
  [productApi.reducerPath]: productApi.reducer,
  [companyApi.reducerPath]: companyApi.reducer,
  [articleApi.reducerPath]: articleApi.reducer,
  [ratingApi.reducerPath]: ratingApi.reducer,
});

function makeStore() {
  return configureStore({
    reducer: rootReducer,
    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware().concat(
        productApi.middleware,
        companyApi.middleware,
        articleApi.middleware,
        ratingApi.middleware,
      ),
  });
}

export const store = makeStore();

export const wrapper = createWrapper<ReturnType<typeof makeStore>>(makeStore);

setupListeners(store.dispatch);
